package com.example.springboot.exception;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.example.springboot.entity.Res;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice  // 让 Spring 识别这是一个全局异常处理器
public class GlobalExceptionHandler {
    // 捕获 TokenExpiredException
    @ExceptionHandler(TokenExpiredException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)  // 返回 401 状态码，表示未授权
    public Res<String> handleTokenExpiredException(TokenExpiredException e) {
        return new Res<String>().code(401).msg("Token has expired: " + e.getMessage()).data(null);
    }

    // 捕获所有异常
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)  // 返回 500 状态码
    public Res<String> handleException(Exception e) {
        return new Res<String>().code(500).msg("Global error occurred: " + e.getMessage()).data(null);
    }

    // 处理特定异常，举例处理非法参数异常
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)  // 返回 400 状态码
    public Res<String> handleIllegalArgumentException(IllegalArgumentException e) {
        return new Res<String>().code(400).msg("Invalid argument: " + e.getMessage()).data(null);
    }
}